package com.ecoolex.ying.space.admin.graphql;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;

import com.ecoolex.framework.modularize.api.auth.admin.AdminMemberAuthority;
import com.ecoolex.framework.modularize.api.auth.annotation.AdminAuthoritativeRegister;
import com.ecoolex.framework.modularize.api.service.config.SystemConfig;
import com.ecoolex.framework.modularize.api.service.storage.FileSize;
import com.ecoolex.framework.modularize.api.service.storage.MimeType;
import com.ecoolex.framework.modularize.api.service.storage.StorageInfo;
import com.ecoolex.framework.modularize.api.service.storage.StorageService;
import com.ecoolex.framework.modularize.api.service.storage.Upload;
import com.ecoolex.framework.modularize.api.service.storage.UploadLimit;
import com.ecoolex.framework.modularize.api.service.storage.UploadSource;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module;
import com.ecoolex.framework.web.api.graphql2.annotation.MutationField;
import com.ecoolex.framework.web.api.graphql2.annotation.QueryField;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module.Type;
import com.ecoolex.ying.space.Constant;
import com.ecoolex.ying.space.admin.core.AdminConstant;

@GraphQL2Module(type = Type.Admin, description = "微信客服管理")
@AdminAuthoritativeRegister(parentKey = AdminConstant.AUTH_MODULE_KEY, key = WeChatGraphql.AUTH, name = "微信客服管理")
public class WeChatGraphql {

	public static final String AUTH = AdminConstant.AUTH_MODULE_KEY + "-WECHAT";
	
	@Autowired
	private StorageService storageService;
	
	@Autowired
	private SystemConfig systemConfig;
	
	private static final String AUTH_GET = AUTH + "-GET";
	
	@QueryField(field = "weChatCustomerServiceImage",description = "微信客服图片")
	@AdminAuthoritativeRegister(parentKey = AUTH, key = AUTH_GET, name = "微信客服图片")
	public StorageInfo weChatCustomerServiceImage(AdminMemberAuthority user) {
		user.assertAuth(AUTH_GET);
		return storageService.get(systemConfig.get(Constant.CONFIG_WECHAT_CUSTOMER_SERVICE_KEY));
	}
	
	private static final String AUTH_UPLOAD = AUTH + "-UPLOAD";
	
	@MutationField(field = "uploadWeChatCustomerServiceImage", description = { "上传微信客服图片" })
	@AdminAuthoritativeRegister(parentKey = AUTH, key = AUTH_UPLOAD, name = "上传微信客服图片")
	public StorageInfo uploadUserWorksCoverImages(@NonNull Upload request,AdminMemberAuthority user) {
		user.assertAuth(AUTH_UPLOAD);
		UploadSource uploadSource = new UploadSource("WechatCustomerService","Image");
        UploadLimit uploadLimit = new UploadLimit();
        uploadLimit.setMaxSize(FileSize.MB.byteLength(2));
        uploadLimit.setAllowMimeType(MimeType.IMAGE.commons());
        

        return storageService.upload(request,uploadSource,uploadLimit,consumer -> {
        	String storageId = consumer.getStorageId();
        	systemConfig.set(Constant.CONFIG_WECHAT_CUSTOMER_SERVICE_KEY, storageId, user.userName());
        });
	}
}
